package com.example.wanandroid.interceptor;

import com.example.wanandroid.pojo.LoginToken;
import com.example.wanandroid.pojo.User;
import com.example.wanandroid.result.Result;
import com.example.wanandroid.result.ResultUtil;
import com.example.wanandroid.service.TokenService;
import com.example.wanandroid.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @Desc 拦截器
 * 用来判断用户的
 * 1. 当preHandle方法返回false时，从当前拦截器往回执行所有拦截器的afterCompletion方法，再退出拦截器链。也就是说，请求不继续往下传了，直接沿着来的链往回跑。
 * 2.当preHandle方法全为true时，执行下一个拦截器,直到所有拦截器执行完。再运行被拦截的Controller。然后进入拦截器链，运
 * 行所有拦截器的postHandle方法,完后从最后一个拦截器往回执行所有拦截器的afterCompletion方法.
 * @Date 2020/4/16 22:18
 */
@Component
public class PassportInterceptor implements HandlerInterceptor {
    @Autowired
    TokenService tokenService;
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器preHandle方法"+request.getRequestURL());
        String token = null;
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals("token_pass")) {
                    token = cookie.getValue();
                    System.out.println("拦截器拦截到的cookie==" + token);
                    break;
                }
            }
        }
        //根据拦截到的cookie往数据库里查询
        LoginToken loginToken = tokenService.selectByToken(token);
        if (loginToken == null || loginToken.getExpiredDate().before(new Date())) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                Result result = ResultUtil.error(10001, "登录失效重新登录");
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(result);
                response.setContentType("application/json");
                out = response.getWriter();
                // 返回json信息给前端
                out.append(json);
                out.flush();
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }
        User user = userService.selectByPrimaryKey(loginToken.getUserId());
        request.setAttribute("userid",loginToken.getUserId());
        request.setAttribute("user",user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
